import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int top = 0;
        int down = matrix.length-1;
        int left = 0;
        int right = matrix[0].length-1;
        while (true){
            for(int i=left;i<=right;i++){
                list.add(matrix[top][i]);
            }
            top++;
            if(top > down) break;
            for (int i=top;i<=down;i++){
                list.add(matrix[i][right]);
            }
            right--;
            if(right < left) break;

            for (int i=right;i>=left;i--){
                list.add(matrix[down][i]);
            }
            down--;
            if(down < top) break;

            for (int i=down;i>=top;i--){
                list.add(matrix[i][left]);
            }
            left++;
            if(left > right) break;
        }
        return list;
    }
}